﻿using AutoMapper;
using MySqlConnector;
using Unit5.DataModel;
using Unit5.Models;
using Unit5.Utils;

namespace Unit5.Service
{
    public class ProductService : IProductService
    {
        private readonly IMapper _mapper;

        public ProductService(IMapper mapper)
        {
            _mapper = mapper;
        }

        public List<ProductViewModel> Search()
        {
            string sql = @"SELECT a.Id,ProductName,CategoryName,Price,a.UpdatedTime,b.NickName AS CreatedNickName,c.NickName AS UpdatedNickName 
            FROM Product a JOIN UserInfo b ON a.createdUserId = b.id JOIN UserInfo c ON a.updatedUserId = c.Id WHERE a.Deleted = 0;";
            return DbHelper.ExecuteQuery<ProductViewModel>(sql);
        }

        public void Add(ProductCreateBo bo)
        {
            // 先将Bo对象 转换为DataModel对象（因为Bo对象不能出现在Repository数据访问层）
            /*var product = new Product()
            {
                Id = IdWorker.Singleton.nextId(),
                CategoryName = bo.CategoryName,
                CreatedUserId = bo.CreatedUserId,
                Price = bo.Price,
                UpdatedUserId = bo.UpdatedUserId,
                ProductName = bo.ProductName,
                Remark = bo.Remark
            };*/
            var product = _mapper.Map<ProductCreateBo, Product>(bo);
            product.Id = IdWorker.Singleton.nextId();

            string sql = "insert into Product values(@Id,@ProductName,@CategoryName,@Price,@Remark,@CreatedUserId,@UpdatedUserId,@CreatedTime,@UpdatedTime,@Deleted)";
            MySqlParameter[] parameters =
            {
                new("@Id",product.Id),
                new("@ProductName",product.ProductName),
                new("@CategoryName",product.CategoryName),
                new("@Price",product.Price),
                new("@Remark",product.Remark),
                new("@CreatedUserId",product.CreatedUserId),
                new("@UpdatedUserId",product.UpdatedUserId),
                new("@CreatedTime",product.CreatedTime),
                new("@UpdatedTime",product.UpdatedTime),
                new("@Deleted",product.Deleted)
            };
           DbHelper.ExecuteCommand(sql, parameters);
        }
    }
}
